package com.hlkj.baojin.utils;


import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.hlkj.baojin.constant.enums.SmsTypeEnum;
import com.mascloud.sdkclient.Client;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@Configuration
public class MoblieMessageUtil {
    private final static Logger logger = LoggerFactory.getLogger(MoblieMessageUtil.class);
    //产品名称:云通信短信API产品,开发者无需替换
    private static final String product = "Dysmsapi";
    //产品域名,开发者无需替换
    private static final String domain = "dysmsapi.aliyuncs.com";

    // TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
    private static final String accessKeyId = "LTAIZvVw1RmuWUOT";
    private static final String accessKeySecret = "suSDZj8sM8tdMZfPXYrhK6EGNsBLD7";

    @Value("${spring.sms.mas.url}")
    private String MAS_URL;
    @Value("${spring.sms.mas.user}")
    private String MAS_USER;
    @Value("${spring.sms.mas.psw}")
    private String MAS_PSW;
    @Value("${spring.sms.mas.ecname}")
    private String MAS_ECNAME;
    //    @Bean
    public Client initClient() {
        Client client = Client.getInstance();
        boolean isLoggedin = client.login(MAS_URL, MAS_USER, MAS_PSW, MAS_ECNAME);
        if (isLoggedin) {
            logger.info("Login successed");
        } else {
            logger.error("Login failed");
//            throw new IllegalArgumentException("短信客户端账号密码错误");
        }
        return client;
    }
    //    @Autowired
    private Client client;

    /** 阿里服务器发送
     * @param phoneNumber
     * @param smsTypeEnum
     * @param param
     * @return
     */
    public static SendSmsResponse sendSmsAli(String phoneNumber, SmsTypeEnum smsTypeEnum, String... param) {
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        try {
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        } catch (ClientException e) {
            e.printStackTrace();
            logger.error("初始化客户端失败");
        }
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(phoneNumber);

        request.setSignName("海梁科技");
        request.setTemplateCode(smsTypeEnum.getCode());
        request.setTemplateParam(smsTypeEnum.getAliString(param));

        //hint 此处可能会抛出异常，注意catch
        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("发送失败，到短信服务器失败");
        }
        System.out.println("短信接口返回的数据----------------");
        System.out.println("Code=" + sendSmsResponse.getCode());
        System.out.println("Message=" + sendSmsResponse.getMessage());
        System.out.println("RequestId=" + sendSmsResponse.getRequestId());
        System.out.println("BizId=" + sendSmsResponse.getBizId());

        return sendSmsResponse;
    }

    public static QuerySendDetailsResponse querySendDetails(String bizId) throws ClientException {

        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象
        QuerySendDetailsRequest request = new QuerySendDetailsRequest();
        //必填-号码
        request.setPhoneNumber("15000000000");
        //可选-流水号
        request.setBizId(bizId);
        //必填-发送日期 支持30天内记录查询，格式yyyyMMdd
        SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
        request.setSendDate(ft.format(new Date()));
        //必填-页大小
        request.setPageSize(10L);
        //必填-当前页码从1开始计数
        request.setCurrentPage(1L);

        //hint 此处可能会抛出异常，注意catch
        QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request);

        return querySendDetailsResponse;
    }

    /** 发送移动云短信
     * @param mobilePhone
     * @param smsTypeEnum
     * @param param
     * @return 是否成功
     */
    public boolean sendSmsMas(String mobilePhone, SmsTypeEnum smsTypeEnum, String... param) {
        String[] mobiles = {mobilePhone};
        client = initClient();
        int sendResult  = client.sendDSMS(mobiles, smsTypeEnum.getMasMsgString(param), "123", 1, "DWItALe3A", "2004563256421", true);
        return sendResult == mobiles.length;
//        if(sendResult == mobiles.length){
//            return true;
//        //失败了初始化在发送一次
//        }else{
//            client = initClient();
//            sendResult  = client.sendDSMS(mobiles, smsTypeEnum.getMasMsgString(param), "123", 1, "DWItALe3A", "2004563256421", true);
//            return sendResult == mobiles.length;
//        }
    }

}